Chapter 9 - Looping over containers

So far, you have been introduced to integers (e.g. 1) strings (e.g. 'hello'), lists (e.g. [1, 'a', 3] , and sets (e.g. {1, 2, 'Python'}). You have learned how to create and inspect them using methods and built-in functions.

However, you'll find that, most of the time, you just want to carry out some operation for all the items in a sequence. Built-in functions and methods are then not always the answer. However, the for-loop is!

The goal of this chapter is to introduce you to the for-loop, which is the most commonly used loop.

At the end of this chapter, you will be able to:

  • loop over a list
  • loop over a set
  • loop over a string
  • work with a new data structure: tuples
  • use two slightly more advanced concepts:
    • break
    • continue

If you want to learn more about these topics, you might find the following links useful:

If you have questions about this chapter, please refer to the forum on Canvas.

1. Looping over a list

Let's look at an example using a for-loop over a list.


In [ ]:
for number in [1,2,3]:
    print(number)

This loop prints the numbers 1, 2, and 3, each on a new line. The variable name number is just something I have chosen. It could have been anything, even something like sugar_bunny. But number is nice and descriptive. OK, so how does the loop work?

  • The Python interpreter starts by checking whether there's anything to iterate over. If the list is empty, it just passes over the for-loop and does nothing.
  • Then, the first value in the iterable (in this case a list) gets assigned to the variable number.
  • Following this, we enter a for-loop context, indicated by the indentation (four spaces preceding the print function). This for-loop context can be as big as you want. All Python cares about is those four spaces. Everything that is indented is part of the for-loop context.
  • Then, Python carries out all the operations in the for-loop context. In this case, this is just print(number). Because number refers to the first element of the list, it prints 1.
  • Once all operations in the for-loop context have been carried out, the interpreter checks if there are any more elements in the list. If so, the next value (in this case 2) gets assigned to the variable number.
  • Then, we move to step 3 again: enter the for-loop context, carry out all the operations, and check if there's another element in the list, and so on, until there are no more elements left.

Please note that if a container (in this case a list) is empty, we will not print anything.


In [ ]:
for number in []:
    print(number)

Loops work extremely well with if-statements


In [ ]:
for item in ['Python', 'is', 'really', 'nice', 'right?']:
    if item.startswith('r'):
        print(item, 'startswith the letter r')
    else:
        print(item, 'does not start with the letter r')

Tip:

You can reverse the order of a list by using list.reverse() or list[::-1]:


In [ ]:
a_list = [1,2,3,4]
a_list.reverse()

for item in a_list:
    print(item)

In [ ]:
a_list = [1,2,3,4]

for item in a_list[::-1]:
    print(item)

2. Looping over a set

It is also possible to loop over a set


In [ ]:
a_set = {'sets', 'are', 'unordered'}
for item in a_set:
    print(item)

3. Looping over a string

Although you might not expect this, you can actually loop over a string.


In [ ]:
word = "hippopotamus"

for letter in word:
    print(letter)

4. Tuples

One data structure (a new one!) is very frequently used with for loops. This data structure is a tuple. It's very simple to create a tuple.


In [ ]:
a_tuple = (1, 'a', 2)
print(a_tuple)
  • A tuple is defined in the same way as a list, except that the whole set of elements is enclosed in parentheses instead of square brackets.
  • The elements of a tuple have a defined order, just like a list.
  • Tuples can contain immutable objects.
  • Tuples can contain mutable objects, but we would advise you to not use sets and lists in tuples
  • Items cannot be added or removed (with some exceptions which are not important here)
  • a tuple can be empty
  • tuples have two methods: index and count

Important for use

  • you can unpack tuples
  • tuples are often used with for-loops

In [ ]:
help(tuple)

A tuple can be empty. You can use () or tuple():


In [ ]:
an_empty_tuple = ()
print(an_empty_tuple)

In [ ]:
another_empty_tuple = tuple()
print(another_empty_tuple)

5. Unpacking variables

It's possible to unpack tuples to separate variables


In [ ]:
a_tuple = (1, 'a', 2)
first_el, second_el, third_el = a_tuple
print(first_el)
print(second_el)
print(third_el)

5.1 Using tuples in a for-loop**

In addition, tuples are often used with for-loops. When working with Python, it's quite common that you end up with data structures like the following example:


In [ ]:
language_data = [('the', 'determiner'),
                 ('house', 'noun'),
                 ('is', 'verb'),
                 ('big', 'adjective')]

Usually, you would like to loop through such an example. One way of doing that is the following:


In [ ]:
for item in language_data:
    print(item[0], item[1])

However, we can unpack the tuple within the for-loop to make it more readable:


In [ ]:
for word, part_of_speech in language_data:
    print(word, part_of_speech)

Note about unpacking

Unpacking is an operation that can also be used with other containers, for instance with lists:


In [ ]:
a_list = [1,2,3]
first_el, second_el, third_el = a_list
print(first_el)
print(second_el)
print(third_el)

6. Continue and break

break

The break statement lets us escape a loop.


In [ ]:
word = "hippopotamus"

for letter in word:
    print(letter)
    if letter =="o":
        break

continue

The continue statement ends the current iteration and jumps to the top of the loop and starts the next iteration.


In [ ]:
word = "hippopotamus"

for letter in word:
    if letter =="o":
        continue
    print(letter)

In the two examples above, not all letters in the word 'hippopotamus' are printed. Both break and continue teleport you to another part of the code. break teleports out of the loop, continue teleports you to the next iteration of the loop.

Exercises

Exercise 1:

Use a loop to print each word in the list in a new line (i.e. only use a single print statement and do not use '\n' to start a new line).


In [ ]:
sentence = 'Now I know a lot about looping'
word_list = sentence.split()

# your code here

Exercise 2:

We have a collection of numbers and want to know how many unique numbers we have. Then we want to print each of them on a single line using a single print statment and not using '\n' to stat a new line.


In [ ]:
number_collection = [1,2,2,3,50, 50, 60, 57, 58, 3, 37, 37]
unique_number = # your code here

# print each number on a single line
# your code here

Exercise 3:

Why might unpacking lists in this way sometimes be a bad idea? Hint: Think of mutability and consider the code below.


In [ ]:
a_list = [1,2,3]
first_el, second_el, third_el = a_list
print(first_el)
print(second_el)
print(third_el)

a_list.append(5)
first_el, second_el, third_el = a_list
print(first_el)
print(second_el)
print(third_el)

In [ ]:
a_list.append(5)
first_el, second_el, third_el = a_list
print(first_el)
print(second_el)
print(third_el)

Exercise 4:

You could even do this with a set. However, not a good idea either? Why? Hint: Think about order.


In [ ]:
a_set = {1,2,3,}
first_el, second_el, third_el = a_set
print(first_el)
print(second_el)
print(third_el)

Exercise 5:

Please use the break statement to make the loop stop after word 'really'


In [ ]:
['Python', 'is', 'really', 'nice', 'right?']
# your code here

Please use the continue statement to make sure that words that start with the letter 'r' are not printed


In [ ]:
['Python', 'is', 'really', 'nice', 'right?']
# your code here

In [ ]: